package com.xq.shop.service.admin.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xq.shop.dao.IAdminDAO;
import com.xq.shop.dao.IBaseDAO;
import com.xq.shop.dao.IMenuDAO;
import com.xq.shop.dao.IPrivilegeDAO;
import com.xq.shop.po.Admin;
import com.xq.shop.po.Menu;
import com.xq.shop.po.Privilege;
import com.xq.shop.po.Role;
import com.xq.shop.service.admin.IAdminService;
import com.xq.shop.vo.Operator;

@Service("admin_admin_service")
public class AdminService extends BaseService<Admin> implements IAdminService {

	@Autowired
	private IAdminDAO adminDAO;
	
	@Autowired
	private IMenuDAO menuDAO;
	
	@Autowired
	private IPrivilegeDAO privilegeDAO;
	
	@Override
	public IBaseDAO<Admin> getDAO() {
		return adminDAO;
	}
	
	@Override
	public Admin get(String username, String password) {
		Admin user = new Admin();
		user.setUsername(username);
		user.setPassword(password);
		return adminDAO.get(user);
	}

	@Override
	public Operator login(Admin admin) {
		
		Operator operator = new Operator();
		if(admin == null || admin.getId() == 0){return operator;}
		
		//获取觉得菜单
		Set<Menu> menu_Set = new HashSet<Menu>();
		
		for(Role role : admin.getRoles()){
			
			menu_Set.addAll(role.getMenus());
		}
		
		operator.getMenu_2nd().addAll(menu_Set);
		
		//获取一级菜单
		List<Long> menu_1st_ids = new ArrayList<Long>();
		
		for(Menu menu : operator.getMenu_2nd()){
			
			Long pID = menu.getParent_id();
			if(pID != null && pID != 0){
				menu_1st_ids.add(pID);
			}
		}
		
		operator.getMenu_1st().addAll(menuDAO.get(menu_1st_ids.toArray(new Long[]{})));
		
		//获取角色权限
		List<Long> ids = new ArrayList<Long>();
		for(Menu menu : operator.getMenu_2nd()){
			ids.add(menu.getId());
		}
		
		for(Privilege p : privilegeDAO.getByMenu(ids)){
			
			operator.getPrivileges().add(p.getUri());
		}
		return operator;
	}

	@Override
	public boolean usernameExists(String username) {
		return adminDAO.get(username).size() > 0;
	}
}
